import 'dart:async';
import 'dart:convert';
import 'dart:math';
import 'dart:typed_data';

import 'package:chat_app_project/util/toast_util.dart';
import 'package:flutter/material.dart';
import 'package:flutter_sound_record/flutter_sound_record.dart';
import 'package:path_provider/path_provider.dart' as syspaths;
import 'package:wukongimfluttersdk/entity/channel.dart';
import 'package:wukongimfluttersdk/model/wk_voice_content.dart';
import 'package:wukongimfluttersdk/wkim.dart';

class VoiceRecord extends StatefulWidget {
  WKChannel currentChannel;

  VoiceRecord({Key? key, required this.currentChannel}) : super(key: key);

  @override
  State<VoiceRecord> createState() => _VoiceRecordState();
}

class _VoiceRecordState extends State<VoiceRecord> {
  //计时定时器
  Timer? _timer;
  //振幅采集定时器
  late Timer _dbs_timer;
  //分贝
  List<int> _dbs = [];
  //计时时间s
  int time = 0;
  //录音文件临时路径
  late String _tmpPath;
  //录音对象
  FlutterSoundRecord record = FlutterSoundRecord();
  @override
  void dispose() {
    super.dispose();
    record.dispose();
    _timer?.cancel();
  }

  requirePermission() async {
    // bool hasPermission = await PermissionUtil.requestAudioPermission();
    var hasPermission = await record.hasPermission();
    if (!hasPermission) {
      ToastUtil.toast("授权异常");
      return;
    }
  }

  startRecord() async {
    _dbs = [];
    time = 0;
    final appDir = await syspaths.getTemporaryDirectory();
    var fileName = "/${Random.secure().nextInt(1000000)}.m4a";
    _tmpPath = '${appDir.path}$fileName';
    // Start recording
    await record.start(
      path: _tmpPath, // required
      encoder: AudioEncoder.AAC, // by default
      bitRate: 128000, // by default
      samplingRate: 44100, // by default
    );
    _timer = Timer.periodic(const Duration(seconds: 1), (Timer t) async {
      bool isRecording = await record.isRecording();
      if (isRecording) {
        time++;
        // ToastUtil.toast("$time");
      }
      setState(() {});
    });
    // double ratio = mediaRecorder.getMaxAmplitude();
    //         double db = 0;// 分贝
    //         if (ratio > 1)
    //             db = 20 * Math.log10(ratio);
    //         Log.e("分贝大小", "--->" + db);
    //         dbs.add((int) db);
    //         mHandler.postDelayed(mUpdateMicStatusTimer, 100);
    _dbs_timer =
        Timer.periodic(const Duration(milliseconds: 100), (Timer t) async {
      bool isRecording = await record.isRecording();
      if (isRecording) {
        record.getAmplitude().then((value) {
          double ratio = value.max;
          double db = 0; // 分贝
          if (ratio > 1) {
            db = 20 * log(ratio);
          }
          debugPrint("分贝大小 ---> $db");
          _dbs.add(db.toInt());
        });
      }
      setState(() {});
    });
  }

  stopRecord(bool send) async {
    debugPrint('结束录音');
    bool isRecording = await record.isRecording();
    if (isRecording) {
      var localPath = await record.stop();
      //分贝采集取消
      _dbs_timer.cancel();
      //录音计时取消
      _timer?.cancel();
      getByte();
      if(send){
        WKVoiceContent voiceContent = WKVoiceContent(time);
        voiceContent.localPath = localPath!;
        voiceContent.waveform = base64Encode(_dbs);
        WKIM.shared.messageManager.sendMessage(
            voiceContent,
            WKChannel(widget.currentChannel.channelID,
                widget.currentChannel.channelType));
        debugPrint('输出路径 $localPath');
      }
    }
  }
  getByte(){
    List<int> bytes=[];
    for (var element in _dbs) {
      ByteData byteData = ByteData(4); // 4 bytes
      byteData.setInt32(0, element);
      List<int> byteArray = byteData.buffer.asUint8List();
      bytes.addAll(byteArray);
    }
    _dbs = bytes;
  //   byte[] bytes = new byte[dbs.size()];
  //   for (int i = 0; i < dbs.size(); i++) {
  //     byte bt = dbs.get(i).byteValue();
  //     if (bt == 0) bt = 2;
  //     bytes[i] = bt;
  //   }
  }
  //手势移动
  Offset _offset = Offset.zero;
  @override
  Widget build(BuildContext context) {
    return Center(
      child: GestureDetector(
        onTap: (){
          requirePermission();
        },
        onLongPress: () {
          // ToastUtil.toast('长按了');
          _offset = Offset.zero;
          startRecord();
        },
        onLongPressEnd: (detail) {
          //向上移动为负值 向下为正值，误差判断为-30 取消发送
          if(_offset.dy < -30){
            stopRecord(false);
            ToastUtil.toast('取消发送');
            return;
          }
          stopRecord(true);
        },
        onLongPressMoveUpdate: (detail) {
          debugPrint('${detail.localOffsetFromOrigin}');
          _offset = detail.localOffsetFromOrigin;
          // ToastUtil.toast('长按下滑了');
          // stopRecord(false);
        },
        child: Image.asset('assets/images/icon_call.png'),
      ),
    );
  }
}
